
const db = require("../database/models");
const Farm_baseinfo = db.farm_baseinfo;
const Op = db.Sequelize.Op;

const Farm_unit_info = db.farm_unit_info;
Farm_baseinfo.hasMany(Farm_unit_info,{
  foreignKey:'pcode',
  sourceKey:'code',
  onDelete:'CASCADE',
  onUpdate:'CASCADE'
});

// Retrieve all from the database.
exports.findAll = (req, res) => {
    const offset = req.query.offset?parseInt(req.query.offset):0;
    const limit = req.query.limit?parseInt(req.query.limit):10;
    const all = req.query.mode==='all'?true:false;
    const hiden = req.query.mode==='hiden'?true:false;
    const mode = all||hiden?false:true;
    const condition = hiden
    ?{
      'deletedAt':{
        [Op.not]:null
      }  
    }
    :{};
    Farm_baseinfo.findAndCountAll({ 
      offset: offset, 
      limit: limit ,
      paranoid:mode,
      where:condition,
      include:{
        model:Farm_unit_info
      }
  
    })
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving farm_baseinfo."
        });
      });
    
  };
  
  // Retrieve a single one with attr and value
  exports.findByAttr = (req, res) => {
    const offset = req.query.offset?parseInt(req.query.offset):0;
    const limit = req.query.limit?parseInt(req.query.limit):10;
    const all = req.query.mode==='all'?true:false;
    const hiden = req.query.mode==='hiden'?true:false;
    const mode = all||hiden?false:true;
  
    const attr = req.params.attr;
    const value = req.params.value;
    const condition = {};
    condition[attr]=value;
    if(!all){
      condition['deletedAt']=hiden
      ?{
          [Op.not]:null 
      }
      :null;
    };
    
    Farm_baseinfo.findAndCountAll({ 
      where: condition , 
      offset:offset,
      limit:limit,
      paranoid:mode,
      include:{
        model:Farm_unit_info
      }
    }).then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving farm_baseinfo."
        });
      });
    
  };
  
  // Find a single one with an id
  exports.findOne = (req, res) => {
      const id = req.params.id;
      const mode = req.query.mode=='all'?false:true;
  
      Farm_baseinfo.findByPk(id,{
        paranoid:mode,
        include:{
          model:Farm_unit_info
        }
      })
        .then(data => {
          res.send(data);
        })
        .catch(err => {
          res.status(500).send({
            message: "Error retrieving Farm_baseinfo with id=" + id
          });
        });
    
  };